<?php

namespace frontend\modules\general\logic;

use common\models\Branch;
use common\models\BranchResource;
use common\models\UserBranch;
use Yii;


/**
 * BranchSearch represents the model behind the search form of `common\models\Branch`.
 */
class DefaultLogic
{
    /**
     * 首页数据缓存10秒
     * @param $branchId
     * @return array
     */
    public function GetBranchIndex($branchId)
    {
        $cache = Yii::$app->cache;
        if ($userNum = $cache->get('branch_index_user') && $data = $cache->get('branch_index_data')) {
            return [$userNum, $data];
        }

        //查询
        $userNum = (new UserBranch())->find()->where(['br_id' => $branchId])->count();

        $data = (new BranchResource())->find()
            ->select(['count(*) AS num', 'sum(look_num) AS look_num', 'type'])
            ->where(['br_id' => $branchId])
            ->groupBy('type')
            ->asArray()
            ->all();

        if (empty($data)) {
            $data[0] = [
                'num' => 0,
                'type' => 0,
                'look_num' => 0,
            ];
        } else {
            $t = $y = 0;
            foreach ($data as $key => $val) {
                $t += $val['num'];
                $y += $val['look_num'];
            }
            $data[] = [
                'num' => $t,
                'type' => 0,
                'look_num' => $y,
            ];
        }
        //cache
        $cache->set('branch_index_user', $userNum, 10);
        $cache->set('branch_index_data', $data, 10);

        return [$userNum, $data];
    }

    /**
     * @return array
     */
    public function UserCenter()
    {
        $data = [];
        $data['username'] = Yii::$app->session->get('branchAdminName');
        $data['br_id'] = Yii::$app->session->get('branchAdminBId');
        $data['phone'] = Yii::$app->session->get('branchPhone');
        $branchInfo = (new Branch())->find()
            ->select(['title', 'start_time', 'end_time',])
            ->where(['id' => $data['br_id']])
            ->asArray()
            ->one();
        $data['title'] = isset($branchInfo['title']) ? $branchInfo['title'] : '';
        $data['time'] = isset($branchInfo['start_time']) ? $branchInfo['start_time'] . ' 至 ' . $branchInfo['end_time'] : '';
        return $data;
    }


}